package jvm;

import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

/**
 * @author Europa
 * @create 2020-05-29 23:07
 */
public class SemaphoreDemo {

    public static void main(String[] args) {
        Semaphore semaphore = new Semaphore(3);

        for (int i = 0; i < 6; i++) {
            Thread thread = new Thread(() -> {
                try {
                    //获取
                    semaphore.acquire();
                    System.out.println(Thread.currentThread().getName() + " 占座");
                    TimeUnit.SECONDS.sleep(1L);
                    System.out.println(Thread.currentThread().getName() + " 离座");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    //释放,不释放程序会继续等待不会结束任务
                    semaphore.release();
                }
            });
            thread.start();
        }
    }
}
